import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/placement/PlaceCustomStepper.dart';
import 'package:ichinesereader/exam/util/ExamUtil.dart';
import 'package:ichinesereader/exam/widgets/BGExamWidget.dart';
import 'package:ichinesereader/exam/widgets/BGSinglePlayer.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'StudentRunningRecordController.dart';

class StudentRunningRecordPage extends GetView<StudentRunningRecordController> {
  const StudentRunningRecordPage(
      {required this.assessmentId, required this.username, Key? key})
      : super(key: key);
  static const String routeName = '/student/runningRecord';
  final String assessmentId;
  final String username;
  @override
  Widget build(BuildContext context) {
    MediaQuery.of(context).size.width;
    if (StrUtil.hasValue(assessmentId) && controller.stepTop.value == -1) {
      controller.loadData(assessmentId, username);
    }
    return Scaffold(
        primary: false,
        body: Container(
            padding: EdgeInsets.all(20),
            decoration: PageStyles().pageBoxDecoration(),
            child: Stack(children: [
              Obx(() {
                return _buildRunningRecordPage(
                    context, controller.stepTop.value);
              }),
              Row(children: [
                Expanded(child: SizedBox()),
                FloatingActionButton(
                    onPressed: () {
                      Get.back();
                    },
                    backgroundColor: Theme.of(context).colorScheme.secondary,
                    child: const Icon(Icons.close_rounded),
                    tooltip: 'Close')
              ])
            ])));
  }

  Widget _buildRunningRecordPage(BuildContext context, int stepNum) {
    return stepNum > 9
        ? Column(children: [
            Expanded(
                child: Scrollbar(
                    thumbVisibility: true,
                    child: SingleChildScrollView(
                        primary: true,
                        child: Container(
                            color: Get.isDarkMode
                                ? AppTheme.colors.darkTheme2
                                : Colors.white,
                            margin: EdgeInsets.all(20),
                            padding: EdgeInsets.all(30),
                            child: _buildExamWidget(context, stepNum))))),
            SizedBox(height: 10),
            _buildSubmitBottom()
          ])
        : Column(
            children: [
              SizedBox(height: 50),
              SizedBox(
                  width: double.infinity,
                  child: Text('Running Records',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize: 32,
                          color: Colors.white,
                          height: 1.2,
                          fontWeight: FontWeight.bold))),
              SizedBox(height: 30),
              StepsWidget(currentIndex: stepNum, isPlacement: false),
              _buildPlaceMain(stepNum),
              SizedBox(height: 20),
              _buildPlaceBottom()
            ],
          );
  }

  Widget _buildExamWidget(BuildContext context, int stepNum) {
    List<Widget> options = [];
    controller.pdfViewerController.firstPage();
    double pdfWidth = MediaQuery.of(context).size.width - 110 > 700
        ? 700
        : MediaQuery.of(context).size.width - 110;
    bool isBigScreen = MediaQuery.of(context).size.width > 1020;
    QuestionPart? part = controller.assessmentResult?.list![stepNum - 10];
    String? pdfUrl = controller
        .assessmentResult!.list![0].questions![0].question![0].head!.pdf;
    if (isBigScreen) {
      options.add(
          Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        ClipOval(
            child: Material(
                color: Color(0xffA2DAE3),
                child: InkWell(
                    child: SizedBox(
                        width: 66,
                        height: 66,
                        child: Icon(Icons.chevron_left,
                            color: Colors.white, size: 50)),
                    onTap: () {
                      controller.pdfViewerController.previousPage();
                    }))),
        SizedBox(
            width: pdfWidth,
            height: pdfWidth * 5 / 7,
            child: SfPdfViewer.network(pdfUrl ?? '',
                controller: controller.pdfViewerController,
                interactionMode: PdfInteractionMode.pan,
                enableDoubleTapZooming: false,
                enableTextSelection: false,
                canShowPaginationDialog: false,
                canShowPasswordDialog: false,
                canShowHyperlinkDialog: false,
                enableHyperlinkNavigation: false,
                enableDocumentLinkAnnotation: false,
                pageLayoutMode: PdfPageLayoutMode.single)),
        ClipOval(
            child: Material(
                color: Color(0xffA2DAE3),
                child: InkWell(
                    child: SizedBox(
                        width: 66,
                        height: 66,
                        child: Icon(Icons.chevron_right,
                            color: Colors.white, size: 50)),
                    onTap: () {
                      controller.pdfViewerController.nextPage();
                    })))
      ]));
    } else {
      options.add(SizedBox(
          width: pdfWidth,
          height: pdfWidth * 5 / 7,
          child: SfPdfViewer.network(pdfUrl ?? '',
              controller: controller.pdfViewerController,
              interactionMode: PdfInteractionMode.pan,
              enableDoubleTapZooming: false,
              enableTextSelection: false,
              canShowPaginationDialog: false,
              canShowPasswordDialog: false,
              canShowHyperlinkDialog: false,
              enableHyperlinkNavigation: false,
              enableDocumentLinkAnnotation: false,
              pageLayoutMode: PdfPageLayoutMode.single)));
      options.add(SizedBox(height: 10));
      options
          .add(Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
        ClipOval(
            child: Material(
                color: Color(0xffA2DAE3),
                child: InkWell(
                    child: SizedBox(
                        width: 66,
                        height: 66,
                        child: Icon(Icons.chevron_left,
                            color: Colors.white, size: 50)),
                    onTap: () {
                      controller.pdfViewerController.previousPage();
                    }))),
        ClipOval(
            child: Material(
                color: Color(0xffA2DAE3),
                child: InkWell(
                    child: SizedBox(
                        width: 66,
                        height: 66,
                        child: Icon(Icons.chevron_right,
                            color: Colors.white, size: 50)),
                    onTap: () {
                      controller.pdfViewerController.nextPage();
                    })))
      ]));
    }

    options.add(SizedBox(height: 10));
    if (stepNum == 10) {
      options.add(ExamUtil
          .buildHeadInfoWidget(part!.questions![0].content!, context));
      var answer = part.questions![0].question![0].answer;
      if (answer == null || answer.isEmpty) {
        BGSinglePlayer().play(part.questions![0].content!.audio);
      }
    }
    for (QuestionSection section in part!.questions!) {
      options.add(BGExamWidget(
          questionItem: section.question![0],
          isRecordSmall: true,
          getAnswer: (value) {
            judgeShowBottomButton();
          },
          mode: BGExamWidgetMode.Test));
    }
    return Column(children: options);
  }

  Widget _buildPlaceMain(int stepNum) {
    String introduction = '';
    if (stepNum > -1 && stepNum < 3)
      introduction =
          controller.assessmentResult?.list![stepNum].introduction ?? '';
    return Expanded(
        child: Column(
      children: [
        const SizedBox(height: 30),
        Container(
            child: _buildIntroduction(introduction, stepNum),
            margin: EdgeInsets.fromLTRB(40, 0, 40, 0),
            padding: EdgeInsets.fromLTRB(50, 30, 50, 30),
            decoration: BoxDecoration(
                border: new Border.all(
                  color: Colors.grey.withOpacity(0.2),
                  width: 1,
                ),
                color:
                    Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
                boxShadow: [
                  BoxShadow(
                    blurRadius: 20,
                    spreadRadius: 0.5,
                    color: Colors.red.withOpacity(0.3),
                  ),
                ])),
        const SizedBox(height: 30),
        SizedBox(
            width: 120,
            height: 50,
            child: MaterialButton(
                color: Color(0xffd1e5b5),
                textColor: Color(0xff4fa397),
                child: Text(stepNum == 3 ? 'OK' : 'Start',
                    style:
                        TextStyle(fontSize: 20, fontWeight: FontWeight.w500)),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(6.0),
                    side: BorderSide(
                      color: Color(0xffa4cc69),
                    )),
                onPressed: () {
                  BGSinglePlayer().stop();
                  if (stepNum == 3) {
                    Get.back();
                  } else {
                    controller.stepTop.value += 10;
                    judgeShowBottomButton();
                  }
                }))
      ],
    ));
  }

  Widget _buildIntroduction(String introduction, int stepNum) {
    if (stepNum < 0) return SizedBox(width: double.infinity, height: 150);
    List<Widget> options = [];
    String titleStr = '';
    String content = '';
    if (stepNum == 3) {
      titleStr = 'Congratulations! You finished your assessment!';
      content = 'Thank you for your time!';
    } else {
      List tempList = introduction.split('\r\n');
      if (tempList.length < 2) {
        return SizedBox(width: double.infinity, height: 240);
      }
      titleStr = tempList[0];
      for (int i = 1; i < tempList.length; i++) {
        content += tempList[i];
      }
    }

    options.add(Text(titleStr,
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: 30,
            color: Get.isDarkMode ? Colors.white70 : Colors.black87,
            fontWeight: FontWeight.w600)));
    options.add(SizedBox(height: 20));
    if (stepNum == 3) {
      options.add(Icon(Icons.check_circle, size: 100, color: Colors.green));
      options.add(SizedBox(height: 10));
    }
    if (stepNum == 0 && content.contains('[||]')) {
      List showList = content.split('[||]');
      options.add(RichText(
          textAlign: TextAlign.center,
          text: TextSpan(
            text: showList[0],
            style: TextStyle(
                fontSize: 20,
                height: 1.8,
                wordSpacing: 1.5,
                color: Get.isDarkMode ? Colors.white70 : Colors.black87),
            children: [
              WidgetSpan(
                  alignment: PlaceholderAlignment.middle,
                  child: Icon(Icons.stop_circle,
                      size: 50,
                      color: Get.isDarkMode ? Colors.white70 : Colors.black26)),
              TextSpan(
                  text: showList[1],
                  style: TextStyle(
                      fontSize: 20,
                      height: 1.8,
                      wordSpacing: 1.5,
                      color: Get.isDarkMode ? Colors.white70 : Colors.black87))
            ],
          )));
    } else {
      options.add(Text(content,
          textAlign: TextAlign.center,
          style: TextStyle(
              fontSize: 20,
              height: 1.8,
              wordSpacing: 1.5,
              color: Get.isDarkMode ? Colors.white70 : Colors.black87)));
    }
    if (stepNum != 3) {
      options.add(SizedBox(height: 10));
      options.add(IconButton(
          iconSize: 40,
          icon: Icon(
            Icons.volume_up,
            color: Colors.orange,
          ),
          onPressed: () {
            String audioUrl =
                'https://resources.ichinesereader.com/media/runingrecords/Instruction${stepNum + 1}.mp3';
            BGSinglePlayer().play(audioUrl);
          }));
    }
    return Column(children: options);
  }

  Widget _buildPlaceBottom() {
    return SizedBox(
        width: double.infinity,
        height: 20,
        child: Text(
            '© iChineseReader ${DateFormat('yyyy').format(DateTime.now()).toString()}',
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: 16,
                color: Color(0xfff8f9fa),
                height: 1.5,
                fontWeight: FontWeight.w500)));
  }

  Widget _buildSubmitBottom() {
    bool isEnable = controller.isShowSubmit.value;
    return MaterialButton(
        minWidth: 140,
        height: 50,
        color: isEnable ? Color(0xffD2E5B5) : Color(0xffADCCC5),
        textColor: isEnable ? Color(0xff4FA397) : Color(0xff6A8A83),
        child: Text('Submit',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(6.0),
            side: BorderSide(
              color: isEnable ? Color(0xffa4cc69) : Color(0xff8AAAA4),
            )),
        onPressed: () {
          if (isEnable) {
            if (controller.stepTop.value == 12) {
              controller.submitReportRecord();
            } else {
              controller.reportRecord();
            }
            controller.stepTop -= 9;
          }
        });
  }

  void judgeShowBottomButton() {
    bool isEnable = true;
    List<QuestionSection>? questions = controller
        .assessmentResult?.list![controller.stepTop.value - 10].questions;
    for (QuestionSection section in questions!) {
      for (QuestionItem item in section.question!) {
        if (item.answer == null || item.answer!.isEmpty) {
          isEnable = false;
        }
      }
    }
    controller.isShowSubmit.value = isEnable;
  }
}
